package com.qs.education.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;

import com.mysql.fabric.Response;
import com.qs.education.bean.api.PageBean;
import com.qs.education.bean.api.ResponseBean;
import com.qs.education.bean.beans.EducationTeacherResponse;
import com.qs.education.bean.caller.ApiPath;
import com.qs.education.bean.entity.EducationQuestion;
import com.qs.education.bean.entity.EducationQuestionExcel;
import com.qs.education.bean.enums.ResponseStatus;
import com.qs.education.bean.service.BaseService;
import com.qs.education.bean.utils.ExcelImportUtil;
import com.qs.education.bean.utils.JsonUtil;
import com.qs.education.service.IQuestionService;

/**
 * @class QuestionServiceImpl
 * @author Jason
 * @description
 * @date Nov 22, 2018 10:31:19 AM
 */
@Service
public class QuestionServiceImpl extends BaseService implements IQuestionService {

	@Override
	public PageBean getQuestionList(EducationQuestion question, Integer currentPage, Integer pageSize) {

		return apiCaller.getAllQuestion(question, currentPage, pageSize);
	}

	@Override
	public ResponseBean deleteQuestionById(Long id) {

		return apiCaller.deleteQuestionById(id);
	}

	/**
	 * 上传excel文件 解析成list 返回给前端 1 返回list 2 返回临时存放路径 3 返回响应信息
	 */
	public Map<String, Object> uploadQuestionExcelFile(HttpServletRequest request, MultipartFile file) {

		// 定义一个临时存放文件的路径
		Map<String, Object> params = new HashMap<>();
		String tempFilePath = null;
		try {
			if (null != file && !file.isEmpty() && ExcelImportUtil.validateExcel(file.getOriginalFilename())) {
				String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
						+ request.getServletContext().getContextPath();
				params.put("url", url);
				// 生成临时的文件,完成传输后再删除 System.getProperty("user.dir") 当前工程路径
				tempFilePath = System.getProperty("user.dir") + File.separator + file.getOriginalFilename();
				System.out.println(tempFilePath);
				// 字节流转文件
				File tempFile = new File(tempFilePath);
				FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);
				params.put("tempFilePath", tempFilePath);

				InputStream is = new FileInputStream(tempFile);
				// 根据版本选择创建Workbook的方式
				Workbook wb = null;
				// 根据文件名判断文件是2003版本还是2007版本
				if (ExcelImportUtil.isExcel2007(file.getOriginalFilename())) {
					wb = new XSSFWorkbook(is);
				} else {
					wb = new HSSFWorkbook(is);
				}
				List<EducationQuestionExcel> list = ExcelValue(wb);
				params.put("list", list);
				params.put("status", ResponseStatus.SUCCESS.toString());

			} else {
				params.put("status", ResponseStatus.FAILED.toString());
			}
		} catch (Exception e) {
			params.put("status", ResponseStatus.FAILED.toString());
			e.printStackTrace();
		}

		return params;
	}

	/**
	 * @Description 将excel表中的信息读出来
	 * @author Jason
	 * @date Nov 27, 2018
	 * @param wb
	 * @return
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	private List<EducationQuestionExcel> ExcelValue(Workbook wb) throws IllegalArgumentException, IllegalAccessException {

		List <EducationQuestionExcel> list = new ArrayList<>();
		
		// 得到第一个shell
		Sheet sheet = wb.getSheetAt(0);
		// 得到Excel的行数
		int totalRows = sheet.getPhysicalNumberOfRows();
		// 总列数
		int totalCells = 0;
		//记录第一行的值
		Row firstRow = sheet.getRow(0);
		//遍历每一行
		for (int r = 1; r < totalRows; r++) {
			//遍历单元格
			Row row = sheet.getRow(r);
			System.out.println(totalRows+"-----"+row.getLastCellNum()+"-----"+row);
			//获取每一行的单元格数
	    	totalCells= row.getPhysicalNumberOfCells();		
	    	//循环设置每个单元格的数据类型为String类型
	    	for (int j = 0; j < totalCells; j++) {
	    		if(row.getCell(j)!=null){
			          row.getCell(j).setCellType(Cell.CELL_TYPE_STRING);
			    }
			}
	    	//获取每个单元格的数据，保存到集合中
	    	EducationQuestionExcel questionExcel = new EducationQuestionExcel();
	    	for (int t = 0; t < totalCells; t++) {	    		
	    		//判断单元格类型是否为空
	    		if(row.getCell(t, row.RETURN_BLANK_AS_NULL)==null){
	    			Cell cell=row.createCell(t); 	    			
	    			cell.setCellValue("NULL");
	    		}
	    		String cellInfo=row.getCell(t).getStringCellValue();
	    		//判断单元格内容是否为空
	    		if(StringUtils.isBlank(cellInfo)){
	    			cellInfo="NULL";
	    		}	    		
	    		// 利用反射将excel上的值 对应到实体
	    		
	    		Field[] fields = questionExcel.getClass().getDeclaredFields();
	    		for(Field field : fields) {
	    			// 设置私有属性可以访问
	    			field.setAccessible(true);
	    			// 将实体属性与第一行的值对应起来
	    			if (field.getName().equals(firstRow.getCell(t).getStringCellValue())) {
	    				field.set(questionExcel, cellInfo);
	    				break;
	    			}
	    		}
			}
	    	//将实体保存到list中
	    	list.add(questionExcel);

			/*row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
			row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
			row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
			row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
			row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
			String id = row.getCell(0).getStringCellValue();
			String title = row.getCell(1).getStringCellValue();
			String description = row.getCell(2).getStringCellValue();
			String image = row.getCell(3).getStringCellValue();
			String type = row.getCell(4).getStringCellValue();
			
			question.setId(id);
			question.setTitle(title);
			question.setDescription(description);
			question.setImage(image);
			question.setType(type);*/
			
		}
		

		return list;
	}

}
